import React, { CSSProperties, Fragment, memo, useEffect, useRef, useState } from "react";
import { Button, Checkbox, ConfigProvider } from 'antd';
import { TypeExcelConfig, TableDataCell, TypeMergeCellBound } from "../../../types";
import { convertCellStyleConfig, getChangeEventValue, makeClassNameList, parsePrice, toastShort } from "../../../utils";
import { CheckboxChangeEvent } from "antd/es/checkbox";
import { CaretRightOutlined, PushpinOutlined } from '@ant-design/icons';
import { CellStyleConfig } from "../../../utils/types";

interface Props {
    tableDataCell: TableDataCell
    onClickCell?: Function
    onClickCellBtn?: Function
    onClickSwitch?: Function
    onInputValueChange?: Function
    onCellCheckedChange?: Function
    onInputValueEditFinish?: Function
    onIsExpandChange?: Function
    cellRowIndex: number
    cellColIndex: number
    cellStyleConfig?: CellStyleConfig
}

const ExcelCell = (props: Props) => {
    const {
        tableDataCell,
        // mergeCellBoundInfo,
        onClickCell,
        onClickCellBtn,
        onClickSwitch,
        onInputValueChange,
        onCellCheckedChange,
        onInputValueEditFinish,
        onIsExpandChange,
        cellColIndex,
        cellRowIndex,
        cellStyleConfig
    } = props;

    const inputRef = useRef<any>(null);
    const [cellContentEditable, setCellContentEditable] = useState<boolean>(false);

    const [cellText, setCellText] = useState<string>("");
    const oldCellText = useRef<string>("");

    const tableCellValueHasChanged = useRef<boolean>(false);

    // console.log("cell-rerender1")

    // useEffect(() => {
    //     console.log("cell-rerender")
    // }, [
    //     tableDataCell,
    //     onClickCell,
    //     onClickCellBtn,
    //     onClickSwitch,
    //     onInputValueChange,
    //     onCellCheckedChange,
    //     onInputValueEditFinish,
    //     onIsExpandChange,
    //     cellColIndex,
    //     cellRowIndex,
    //     cellStyleConfig
    // ]);

    useEffect(() => {
        if (tableDataCell && tableDataCell.text) {
            const cellText = tableDataCell.text;
            oldCellText.current = tableDataCell.text;
            setCellText(cellText)
        }
    }, [
        tableDataCell,
    ]);

    useEffect(() => {
        if (cellContentEditable) {
            inputRef.current?.focus();
        }
    }, [cellContentEditable]);

    const handleClickCellBtn = (e: any) => {
        onClickCellBtn && onClickCellBtn(tableDataCell);
        e.preventDefault();
        e.stopPropagation();
    };

    const onCellBtnMouseDown = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
    };

    const onChange = (e: CheckboxChangeEvent) => {
        console.log("onChange", e)
        onCellCheckedChange && onCellCheckedChange(tableDataCell, e);
    };

    const onClickSwitchTag = (e: any) => {
        onClickSwitch && onClickSwitch(tableDataCell);
        e.preventDefault();
        e.stopPropagation();
    };

    const stopMouseDown = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
    }

    const onTextInputChange = (e: any): any => {
        let value = getChangeEventValue(e);
        if (tableDataCell && tableDataCell.valueType == 'number') {
            value = value.replace(/[^\d^\.]+/g, '');
            let arr1 = value.split('.');
            if (arr1.length > 2) {
                toastShort('warning', '只能输入一个小数点')
                return false;
            } else {
                if (arr1[1] && arr1[1].length > 2) {
                    toastShort('warning', '只能输入一个小数点后两位数')
                    return false;
                }
            }
        } else {

        }
        if (oldCellText.current != value) {
            console.log("cell文本已改变", oldCellText.current, value )
            tableCellValueHasChanged.current = true;
        } else {
            console.log("cell文本未改变")
            tableCellValueHasChanged.current = false;
        }
        setCellText(value)
        
    };

    const onInputBlur = () => {
        if (tableCellValueHasChanged.current) {
            // onInputValueChange && onInputValueChange(tableDataCell, value);
            onInputValueEditFinish && onInputValueEditFinish(tableDataCell, cellText)
            setCellContentEditable(false)
        } else {
            console.log("由于Cell文本未改变，不触发blur事件")
        }
    }

    const render_cell = () => {
        const cellInlineStyleConfig = convertCellStyleConfig('inline', cellStyleConfig);
        switch (tableDataCell.type) {
            case 'text':
                if (tableDataCell.headLess) {
                    return null
                }
                if (cellContentEditable) {
                    cellInlineStyleConfig.userSelect = 'auto';
                    if (cellInlineStyleConfig.verticalAlign) {
                        return (
                            <p
                                className="excel-cell-text"
                                style={cellInlineStyleConfig}
                            >
                                <span style={{ verticalAlign: cellInlineStyleConfig.verticalAlign }}>{cellText}</span>
                            </p>
                        )
                    }
                    return (
                        <p
                            className="excel-cell-text"
                            style={cellInlineStyleConfig}
                        >
                            {cellText}
                        </p>
                    )
                } else {
                    cellInlineStyleConfig.userSelect = 'none';
                    if (cellInlineStyleConfig.verticalAlign) {
                        return (
                            <p
                                className="excel-cell-text"
                                style={cellInlineStyleConfig}
                            >
                                <span style={{ verticalAlign: cellInlineStyleConfig.verticalAlign }}>{cellText}</span>
                            </p>
                        )
                    }
                    return (
                        <span
                            className="excel-cell-text"
                            style={cellInlineStyleConfig}
                        >
                            {cellText}
                        </span>
                    )
                }
                break;
            case 'button':
                return (
                    <Button
                        className="excel-cell-btn"
                        color="#00b578"
                        type="primary"
                        onClick={handleClickCellBtn}
                        onMouseDown={onCellBtnMouseDown}
                    >
                        {tableDataCell.text}
                    </Button>
                )
                break;
            case 'input':
                if (cellContentEditable) {
                    return (
                        <input
                            ref={inputRef}
                            type={tableDataCell.valueType && tableDataCell.valueType == 'number' ? 'number' : 'text'}
                            value={cellText}
                            className={'excel-inner-input'}
                            onChange={onTextInputChange}
                            onBlur={onInputBlur}
                            style={cellInlineStyleConfig}
                        />
                    )
                }
                if (cellInlineStyleConfig.verticalAlign) {
                    return (
                        <p
                            className="excel-cell-text"
                            style={cellInlineStyleConfig}
                        >
                            <span style={{ verticalAlign: cellInlineStyleConfig.verticalAlign }}>{cellText}</span>
                        </p>
                    )
                }
                return (
                    <p
                        className="excel-cell-text"
                        style={cellInlineStyleConfig}
                    >
                        {tableDataCell.valueType && tableDataCell.valueType == 'number' ? parsePrice(Number(cellText)) : cellText}
                    </p>
                )
                break;
            case 'expand':
                return (
                    <div className="flex-row excel-cell-expand">
                        <div
                            className="excel-cell-expand-icon-containr"
                            style={{ transform: tableDataCell.isExpand ? 'rotateZ(90deg)' : 'rotateZ(0deg)' }}
                        >
                            <CaretRightOutlined className="excel-cell-expand-icon" />
                        </div>
                        <p className="excel-cell-text">{tableDataCell.text}</p>
                    </div>
                )
                break;
            case 'select':
                return (
                    <ConfigProvider
                        theme={{
                            token: {
                                colorPrimary: '#00b578',
                            },
                        }}
                    >
                        <Checkbox onChange={onChange} checked={tableDataCell.isChecked} />
                    </ConfigProvider>

                )
                break;
            case 'switch':
                return (
                    <Fragment>
                        <p
                            className="excel-cell-text"
                            style={cellInlineStyleConfig}
                        >
                            {tableDataCell.text}
                        </p>
                        <div
                            className="excel-cell-switch-tag"
                            style={Number(tableDataCell.text) == 0 ? { opacity: 1 } : { opacity: 0.36, pointerEvents: 'none' }}
                            title={'填入投资金额'}
                        >
                            <div
                                className="excel-cell-switch-tag-content"
                                onClick={onClickSwitchTag}
                                onMouseDown={stopMouseDown}
                            >
                                <PushpinOutlined />
                            </div>
                        </div>
                    </Fragment>
                )
                break;
            default:
                break;
        }
    };

    const getCellContentStyle = (): CSSProperties => {
        try {
            let cellContentStyle: CSSProperties = {};
            if (tableDataCell && tableDataCell.cellStyle) {
                cellContentStyle = {
                    ...cellContentStyle,
                    ...tableDataCell.cellStyle,
                };
            }

            const cellBlockStyleConfig = convertCellStyleConfig('block', cellStyleConfig);
            cellContentStyle = {
                ...cellContentStyle,
                ...cellBlockStyleConfig
            }
            return cellContentStyle;
        } catch (e) {
            return {};
        }
    };

    const onClickCellContent = (e: any) => {
        // const { onClickCell, onIsExpandChange } = props;
        // if (tableDataCell && tableDataCell.type) {
        //     switch (tableDataCell.type) {
        //         case 'expand':
        //             onIsExpandChange && onIsExpandChange(tableDataCell, e);
        //             break;
        //         default:
        //             onClickCell && onClickCell(tableDataCell)
        //             break;
        //     }
        // }
    };

    const onDoubleClickCellContent = () => {
        if (tableDataCell.type && tableDataCell.type == 'text') {
            toastShort("warning", "该单元格不可编辑");
            return false;
        }
        setCellContentEditable(true)
    }

    const onCellContentMouseDown = (e: any) => {
        // if (tableDataCell && ['expand'].includes(tableDataCell.type)) {
        //     e.preventDefault();
        //     e.stopPropagation();
        // }
    };

    return (
        <div
            className={makeClassNameList([
                'flex-row excel-cell-content',

            ])}
            style={getCellContentStyle()}
            onClick={onClickCellContent}
            onDoubleClick={onDoubleClickCellContent}
            onMouseDown={onCellContentMouseDown}
        >
            {
                tableDataCell && tableDataCell.type == 'input' && tableDataCell.editble ?
                    <div className="table-cell-angle">
                        <div className="table-cell-angle-content"></div>
                    </div>
                    :
                    null
            }
            {
                tableDataCell && tableDataCell.id ?
                    render_cell()
                    :
                    null
            }
        </div>
    )
};

const checkUpdate = (prevProps: Props, nextProps: Props): boolean => {
    console.log("prevProps---->", prevProps);
    console.log("nextProps---->", nextProps);
    let dotNeedUpdate = prevProps.cellColIndex == nextProps.cellColIndex;
    return true;
}

export default memo(ExcelCell);